package com.vichat.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vichat.api.entity.RequestBusiRecord;
import com.vichat.api.entity.ResponseBusiRecord;
import com.vichat.api.service.IApiService;
import com.vichat.api.util.CheckUtil;
import com.vichat.api.vo.*;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.threads.SysMsgThread;
import com.vichat.common.util.DateUtil;
import com.vichat.common.util.Md5Util;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.vo.SysMsg;
import com.vichat.gps.entity.LocationData;
import com.vichat.gps.service.IGpsService;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.entity.RoomMember;
import com.vichat.room.service.IRoomService;
import com.vichat.user.cache.StaticDataCache;
import com.vichat.user.entity.SysStaticData;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.entity.UserOrg;
import com.vichat.user.entity.UserParty;
import com.vichat.user.service.IUserService;
import com.vichat.user.vo.CompanyVO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by wangluyin on 2017/12/18.
 */

@Controller
@RequestMapping("/api")
public class ApiController {
    private static Log logger = LogFactory.getLog(ApiController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    StaticDataCache staticDataCache;

    @Autowired
    IApiService apiService;


    private ExecutorService tp = Executors.newCachedThreadPool();

    @Autowired
    IUserService userService;

    @Autowired
    IRoomService roomService;


    @Autowired
    private IGpsService gpsService;


    HashMap<String, String> companyTokenMap = new HashMap();
    HashMap<String, String> systemTokenMap = new HashMap();


    private static boolean isValidSign(String token, String timestamp, String sign) {
        String md5Value = Md5Util.Md5Encode(token + timestamp, null);
        if (StringUtils.equals(md5Value, sign)) {
            return true;
        } else {
            return false;
        }
    }


    @RequestMapping("/post")
    @ResponseBody
    public ResponseBusiRecord post(@RequestBody RequestBusiRecord requestBusiRecord) {
        ResponseBusiRecord responseBusiRecord = new ResponseBusiRecord();
        try {
            BeanUtils.copyProperties(responseBusiRecord, requestBusiRecord);
            String appId = requestBusiRecord.getAppId();
            String appType = requestBusiRecord.getAppType();
            String token = getToken(appId, appType);
            if (token == null) {
                throw new Exception("appId:" + appId + "不合法");
            }
            boolean isValid = isValidSign(token, requestBusiRecord.getTimestamp(), requestBusiRecord.getSign());
            if (!isValid) {
                throw new Exception("sign:" + requestBusiRecord.getSign() + "不合法");
            }
            responseBusiRecord = doPost(requestBusiRecord);
        } catch (Exception e) {
            e.printStackTrace();
            responseBusiRecord.setResponseCode("99");
            responseBusiRecord.setResponseMsg(e.getMessage());
            logger.error("api/post", e);
        }
        return responseBusiRecord;
    }


    public ResponseBusiRecord doPost(RequestBusiRecord request) {
        ResponseBusiRecord response = null;
        try {

            logger.info("RequestBusiRecord:" + JSON.toJSONString(request));
            response = ResponseBusiRecord.convert(request);
            String sign = Md5Util.Md5Encode(this.getToken(response.getAppId(), request.getAppType()) + response.getTimestamp(), null);
            response.setSign(sign);


            JSONObject json = JSONObject.parseObject(request.getRequestContent());

            if (request.getMethod().equals("vc.register_company") && "S".equalsIgnoreCase(request.getAppType())) {// 注册企业
                registerCompany(response, json);
            } else if (request.getMethod().equals("vc.add_user")) {// 人员添加接口
                addUser(response, json);
            } else if (request.getMethod().equals("vc.mod_user")) {// 人员修改接口
                modUser(response, json);
            } else if (request.getMethod().equals("vc.del_user")) {// 人员删除接口
                delUser(response, json);
            } else if (request.getMethod().equals("vc.reset_passwd")) {// 密码修改接口
                resetPasswd(response, json);
            } else if (request.getMethod().equals("vc.activity_user")) {// 用户激活(延期)接口
                acitivityUser(response, json);
            } else if (request.getMethod().equals("vc.add_room")) {// 频道添加接口
                addRoom(response, json);
            } else if (request.getMethod().equals("vc.mod_room")) {// 频道修改接口
                modRoom(response, json);
            } else if (request.getMethod().equals("vc.del_room")) {// 频道删除接口
                delRoom(response, json);
            } else if (request.getMethod().equals("vc.add_roomuser")) {// 频道成员添加接口
                addRoomUser(response, json);
            } else if (request.getMethod().equals("vc.del_roomuser")) {// 频道成员删除接口
                delRoomUser(response, json);
            } else if (request.getMethod().equals("vc.get_locationlog")) {// 获取定位轨迹
                getLocationLog(response, json);
            } else if (request.getMethod().equals("vc.get_onlinelocation")) {// 获取在线用户定位
                getOnlineLocation(response, json);
            } else if (request.getMethod().equals("vc.get_selectuserlocation")) {// 获取勾选用户定位
                getSelectLocation(response, json);
            } else if (request.getMethod().equals("vc.location_switch")) {// 人员定位接口
                locationSwitch(response, json);
            } else if (request.getMethod().equals("vc.create_personal_room")) {// 添加临时频道
                createPersonalRoom(response, json);
            } else if (request.getMethod().equals("vc.add_org")) {// 添加组织
                addOrg(response, json);
            } else if (request.getMethod().equals("vc.mod_org")) {// 修改组织(名称)
                modOrg(response, json);
            } else if (request.getMethod().equals("vc.del_org")) {// 删除组织
                delOrg(response, json);
            } else if (request.getMethod().equals("vc.share_video")) {// 分享视频
                shareVideo(response, json);
            }

            //apiService.backRequestBusiRecord(request);
            //apiService.saveResponseBusiRecord(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
            logger.debug("JSON REQUEST:" + JSON.toJSONString(request));
            logger.debug("JSON RESPONSE:" + JSON.toJSONString(response));
            return response;
        }
    }

    private ResponseBusiRecord registerCompany(ResponseBusiRecord response, JSONObject json) {
        Company rtnCompany = new Company();
        JSONObject content = new JSONObject();
        try {
            JSONObject companyObj = json.getJSONObject("company");
            String companyName = companyObj.getString("companyName");
            String ext = companyObj.getString(response.getAppId());
            CompanyVO vo = userService.registerCompanyNoAdmin(companyName, ext, NumberUtils.toLong(response.getAppId()));
            saveApiBusiRecord(response, vo.getParty().getPartyId(), null, null);
            response.setResponseCode("0000");
            BeanUtils.copyProperties(rtnCompany, vo.getParty());
            Org org = new Org();
            BeanUtils.copyProperties(org, vo.getOrg());
            rtnCompany.setOrg(org);
            rtnCompany.setCompanyName(vo.getParty().getPartyName());
        } catch (Exception e) {
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
            rtnCompany.setResultCode("0099");
            rtnCompany.setResultMsg(e.getMessage());
        }
        content.put("company", rtnCompany);
        response.setResponseContent(content.toString());


        return response;
    }

    private void addUser(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            List<UserBasic> users = JSONArray.parseArray(json.get("user").toString(), UserBasic.class);
            List<User> rtnUsers = new ArrayList<User>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            for (UserBasic user : users) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    user.setUid(null);
                    CheckUtil.checkAddUser(user);

                    if (partyId != 0 && user.getPartyId().longValue() != partyId) {
                        throw new Exception("参数partyId数据异常");
                    }

                    user.setIccid(null);
                    userService.saveUserBasic(user);
                    userService.updateUserBasicVersion(user.getUid());
                    saveApiBusiRecord(response, user.getPartyId(), user.getUid(), null);
                    BeanUtils.copyProperties(rtnUser, user);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("人员添加接口", e);
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                }
                rtnUsers.add(rtnUser);
            }
            content.put("user", rtnUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void modUser(ResponseBusiRecord response, JSONObject json) {

        JSONObject content = new JSONObject();
        try {
            List<UserBasic> users = JSONArray.parseArray(json.get("user").toString(), UserBasic.class);
            List<User> rtnUsers = new ArrayList<User>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            for (UserBasic user : users) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    CheckUtil.checkModUser(user);
                    if (partyId != 0 && user.getPartyId().longValue() != partyId) {
                        throw new Exception("参数partyId数据异常");
                    }
                    // @todo 处理修改名字的情况，需要刷新频道内名字
                    UserBasic userFDB = userService.getUserBasicByUid(user.getUid());
                    if (userFDB == null) {
                        throw new Exception("uid:" + user.getUid() + " 的用户不存在");
                    }

                    if (!StringUtils.equals(userFDB.getUserName(), user.getUserName())) {
                        roomService.updateUserName(userFDB.getUid(), user.getUserName());
                    }
                    userService.saveUserBasic(user);
                    userService.updateUserBasicVersion(user.getUid());
                    saveApiBusiRecord(response, userFDB.getPartyId(), userFDB.getUid(), null);
                    BeanUtils.copyProperties(rtnUser, userFDB);
                } catch (Exception e) {
                    logger.info("人员修改接口1" + e.getMessage(), e);
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                    e.printStackTrace();
                }
                rtnUsers.add(rtnUser);
            }
            content.put("user", rtnUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            logger.info("人员修改接口2" + e.getMessage(), e);
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void delUser(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            List<UserBasic> users = JSONArray.parseArray(json.get("user").toString(), UserBasic.class);
            List<User> rtnUsers = new ArrayList<User>();
            List<Long> delUserList = new ArrayList<>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            for (UserBasic user : users) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    CheckUtil.checkModUser(user);
                    if (partyId != 0 && user.getPartyId().longValue() != partyId) {
                        throw new Exception("参数partyId数据异常");
                    }
                    userService.delUserBasic(user.getPartyId(), user.getUid());
                    userService.updateUserBasicVersion(user.getUid());
                    roomService.delRoomMemberLogicallyByUid(user.getUid());

                    saveApiBusiRecord(response, user.getPartyId(), user.getUid(), null);

                    delUserList.add(user.getUid());
                } catch (Exception e) {
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                    e.printStackTrace();
                    logger.error("人员删除接口", e);
                }
                rtnUsers.add(rtnUser);
            }
            if (!delUserList.isEmpty()) {
                String delUserIdStr = StringUtils.join(delUserList, ",");
            }
            content.put("user", rtnUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void resetPasswd(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            List<UserBasic> users = JSONArray.parseArray(json.get("user").toString(), UserBasic.class);
            List<User> rtnUsers = new ArrayList<User>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            for (UserBasic user : users) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    CheckUtil.checkResetPasswd(user);
                    UserBasic userFDB = userService.getUserBasicByUid(user.getUid());
                    if (userFDB == null) {
                        throw new Exception("uid:" + user.getUid() + " 的用户不存在");
                    }
                    if (partyId != 0 && userFDB.getPartyId().longValue() != partyId) {
                        throw new Exception("参数partyId数据异常");
                    }
                    String newPwd = Md5Util.Md5Encode(user.getPassword(), null);
                    newPwd = Md5Util.Md5Encode(newPwd, null);
                    userFDB.setPassword(newPwd);
                    userService.updUserPwd(userFDB);
                    userService.updateUserBasicVersion(userFDB.getUid());
                    saveApiBusiRecord(response, user.getPartyId(), user.getUid(), null);
                    BeanUtils.copyProperties(rtnUser, userFDB);

                } catch (Exception e) {
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                    e.printStackTrace();
                    logger.error("密码修改接口", e);
                }
                rtnUsers.add(rtnUser);
            }
            content.put("user", rtnUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void acitivityUser(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            List<UserBasic> users = JSONArray.parseArray(json.get("user").toString(), UserBasic.class);
            List<User> rtnUsers = new ArrayList<User>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            for (UserBasic user : users) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    CheckUtil.checkAcitivityUser(user);
                    if (partyId != 0) {
                        user.setPartyId(partyId);
                    }
                    UserBasic userFDB = userService.activateUser(user.getPartyId(), user.getUid(), user.getExpiredDate());
                    userService.updateUserBasicVersion(userFDB.getUid());
                    BeanUtils.copyProperties(rtnUser, userFDB);
                    saveApiBusiRecord(response, userFDB.getPartyId(), userFDB.getUid(), null);
                } catch (Exception e) {
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                    e.printStackTrace();
                    logger.error("用户激活(延期)接口", e);
                }
                rtnUsers.add(rtnUser);
            }
            content.put("user", rtnUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void addRoom(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            RoomBasic roomBasic = JSONObject.parseObject(json.get("room").toString(), RoomBasic.class);
            Room rtnRoom = new Room();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            try {

                CheckUtil.checkAddRoom(roomBasic);
                if (partyId != 0 && roomBasic.getPartyId().longValue() != partyId) {
                    throw new Exception("参数partyId数据异常");
                }
                if (NumberUtils.isNullOrZero(roomBasic.getOrgId())) {//如果orgId为空
                    UserOrg rootOrg = userService.getRootOrgByPartyId(roomBasic.getPartyId());
                    if (rootOrg != null) {
                        roomBasic.setOrgId(rootOrg.getOrgId());
                        roomBasic.setOrgCode(rootOrg.getOrgCode());
                    }
                } else {
                    UserOrg org = userService.queryUserOrgByOrgId(roomBasic.getOrgId());
                    if (org != null) {
                        roomBasic.setOrgId(org.getOrgId());
                        roomBasic.setOrgCode(org.getOrgCode());
                    } else {
                        throw new Exception("参数orgId数据异常");
                    }
                }
                initRoomBasic(roomBasic);
                RoomBasic roomFDB = roomService.saveRoomBasic(roomBasic);
                roomService.updateRoomBasicVersion(roomFDB.getRid());
                BeanUtils.copyProperties(rtnRoom, roomFDB);
                saveApiBusiRecord(response, roomFDB.getPartyId(), null, roomFDB.getRid());
            } catch (Exception e) {
                rtnRoom.setErrorResultCode();
                rtnRoom.setResultMsg(e.getMessage());
                e.printStackTrace();
                logger.error("频道添加接口", e);
            }
            content.put("room", rtnRoom);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void modRoom(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            RoomBasic roomBasic = JSONObject.parseObject(json.get("room").toString(), RoomBasic.class);
            Room rtnRoom = new Room();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            try {
                BeanUtils.copyProperties(rtnRoom, roomBasic);
                CheckUtil.checkModRoom(roomBasic);
                RoomBasic roomBasicFDB = roomService.getRoomBasicByRid(roomBasic.getRid());
                if (partyId != 0 && roomBasicFDB.getPartyId().longValue() != partyId) {
                    throw new Exception("参数partyId数据异常");
                }
                initRoomBasic(roomBasic);
                roomBasicFDB = roomService.saveRoomBasic(roomBasic);
                roomService.updateRoomBasicVersion(roomBasicFDB.getRid());
                BeanUtils.copyProperties(rtnRoom, roomBasicFDB);
                saveApiBusiRecord(response, roomBasicFDB.getPartyId(), null, roomBasicFDB.getRid());
            } catch (Exception e) {
                rtnRoom.setErrorResultCode();
                rtnRoom.setResultMsg(e.getMessage());
                e.printStackTrace();
                logger.error("频道修改接口", e);
            }
            content.put("room", rtnRoom);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void delRoom(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            Room room = JSONObject.parseObject(json.get("room").toString(), Room.class);
            Room rtnRoom = new Room();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            try {
                BeanUtils.copyProperties(rtnRoom, room);
                room.check();

                RoomBasic roomFDB = roomService.getRoomBasicByRid(room.getRid());
                if (partyId != 0 && roomFDB.getPartyId().longValue() != partyId) {
                    throw new Exception("参数partyId数据异常");
                }
                if (room.getPartyId().longValue() != roomFDB.getPartyId().longValue()) {
                    throw new Exception("参数partyId数据异常");
                }

                roomFDB = roomService.delRoomBasic(room.getRid());
                BeanUtils.copyProperties(rtnRoom, roomFDB);
                roomService.updateRoomBasicVersion(room.getRid());

                saveApiBusiRecord(response, roomFDB.getPartyId(), null, roomFDB.getRid());
            } catch (Exception e) {
                rtnRoom.setErrorResultCode();
                rtnRoom.setResultMsg(e.getMessage());
                e.printStackTrace();
                logger.error("频道删除接口", e);
            }
            content.put("room", rtnRoom);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void addRoomUser(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            RoomUser roomUsers = JSONObject.parseObject(json.get("roomUser").toString(), RoomUser.class);
            RoomUser rtnRoomUsers = new RoomUser();
            List<User> rtnUsers = new ArrayList<User>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            roomUsers.check();

            RoomBasic roomBasic = roomService.getRoomBasicByRid(roomUsers.getRid());
            if (partyId != 0 && roomBasic.getPartyId().longValue() != partyId) {
                throw new Exception("参数partyId数据异常");
            }
            if (roomBasic.getPartyId().longValue() != roomUsers.getPartyId().longValue()) {
                throw new Exception("partyId和rId不匹配");
            }
            for (User user : roomUsers.getUsers()) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    if (NumberUtils.isNullOrZero(user.getUid())) {
                        throw new Exception("缺少参数uid");
                    }

                    UserBasic userBasicFDB = userService.getUserBasicByUid(user.getUid());
                    if (userBasicFDB == null) {
                        throw new Exception("uid:" + user.getUid() + " 的用户不存在");
                    }
                    if(!GlobalConstant.SUPPORT_ADMIN_LOGIN_APP && userBasicFDB.getUserType() == GlobalConstant.USER_TYPE_2){
                        throw new Exception("禁止添加管理员");
                    }
                    if (roomBasic.getPartyId().longValue() != userBasicFDB.getPartyId().longValue()) {
                        throw new Exception("参数partyId和uid不匹配");
                    }
                    RoomMember roomMember = new RoomMember();
                    roomMember.setUid(user.getUid());
                    roomMember.setRid(roomBasic.getRid());
                    roomMember.setUserName(userBasicFDB.getUserName());
                    roomMember.setAdminGrade(5L);
                    roomService.saveRoomMember(roomMember);

                    roomService.updateRoomMemberVersion(user.getUid(),roomBasic.getRid());

                    saveApiBusiRecord(response, roomUsers.getPartyId(), roomMember.getUid(), roomMember.getRid());
                } catch (Exception e) {
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                    e.printStackTrace();
                    logger.error("频道用户添加接口", e);
                }
                rtnUsers.add(rtnUser);
            }
            roomService.updateRoomBasicVersion(roomBasic.getRid());

            rtnRoomUsers.setUsers(rtnUsers);
            content.put("roomUser", rtnRoomUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void delRoomUser(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            RoomUser roomUsers = JSONObject.parseObject(json.get("roomUser").toString(), RoomUser.class);
            RoomUser rtnRoomUsers = new RoomUser();
            List<User> rtnUsers = new ArrayList<User>();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            roomUsers.check();

            RoomBasic roomBasicFDB = roomService.getRoomBasicByRid(roomUsers.getRid());
            if (partyId != 0 && roomBasicFDB.getPartyId().longValue() != partyId) {
                throw new Exception("参数partyId数据异常");
            }
            if (roomBasicFDB.getPartyId().longValue() != roomUsers.getPartyId().longValue()) {
                throw new Exception("rId对应的partyId与请求报文中不一致");
            }
            for (User user : roomUsers.getUsers()) {
                User rtnUser = new User();
                try {
                    BeanUtils.copyProperties(rtnUser, user);
                    if (NumberUtils.isNullOrZero(user.getUid())) {
                        throw new Exception("缺少参数uid");
                    }
                    roomService.delRoomMemberLogically(roomUsers.getRid(), user.getUid());
                    saveApiBusiRecord(response, roomUsers.getPartyId(), user.getUid(), roomUsers.getRid());
                } catch (Exception e) {
                    rtnUser.setErrorResultCode();
                    rtnUser.setResultMsg(e.getMessage());
                    e.printStackTrace();
                    logger.error("频道用户删除接口", e);
                }
                rtnUsers.add(rtnUser);
            }

            rtnRoomUsers.setUsers(rtnUsers);
            content.put("roomUser", rtnRoomUsers);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void getLocationLog(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            LocationDataVO queryBean = JSONObject.parseObject(json.get("locationData").toString(), LocationDataVO.class);
            CheckUtil.checkGetLocationLog(queryBean);
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            UserBasic userFDB = userService.getUserBasicByUid(queryBean.getUid());
            if (userFDB == null) {
                throw new Exception("uid:" + queryBean.getUid() + " 的用户不存在");
            }
            if (partyId != 0 && userFDB.getPartyId().longValue() != partyId) {
                throw new Exception("参数partyId数据异常");
            }
            queryBean.setTel(userFDB.getPhone());

            LocationData locationData = new LocationData();
            BeanUtils.copyProperties(locationData, queryBean);
            List<LocationData> locationLogList = new ArrayList<LocationData>();
            List<LocationData> locationLogFDB = gpsService.getLocationDatasByUid(locationData.getUid(), DateUtil.getFormattedDate(queryBean.getQueryDate(), "yyyyMMdd"));
            if (locationLogFDB != null && locationLogFDB.size() > 0) {
                for (LocationData data : locationLogFDB) {
                    data.setUserName(userFDB.getUserName());
                }
            }
            String locationDataJson = RedisHelper.getUserLocationData(locationData.getUid());

            if (StringUtils.isNotBlank(locationDataJson)) {
                LocationData locationDataFDB = JSONObject.parseObject(locationDataJson, LocationData.class);

                if (DateUtil.isSameDate(new Date(locationDataFDB.getLocTime()), queryBean.getQueryDate())) {// 非当天的不提供
                    locationDataFDB.setLocId(-1L);//
                    locationDataFDB.setUserName(userFDB.getUserName());
                    locationLogList.add(locationDataFDB);
                }
            }
            if (locationLogList.size() > 0) {
                locationLogList.addAll(locationLogFDB);
                content.put("locationData", locationLogList);
            } else {
                content.put("locationData", locationLogFDB);
            }

            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void getOnlineLocation(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            JSONObject companyObj = json.getJSONObject("company");
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            if (partyId == 0) {
                partyId = companyObj.getLongValue("partyId");
            }
            if (NumberUtils.isNullOrZero(partyId)) {
                throw new Exception("缺少参数partyId");
            }
            UserBasic queryBean = new UserBasic();
            queryBean.setPartyId(partyId);
            queryBean.setDisplayState(GlobalConstant.DISPLAY_STATE_1);
            List<UserBasic> onlineUsers = userService.getOnlineUsers(queryBean);
            List<LocationData> onlineLocations = new ArrayList<>();
            if (!onlineUsers.isEmpty()) {
                Date today = new Date();
                for (UserBasic val : onlineUsers) {
                    String locationDataJson = RedisHelper.getUserLocationData(val.getUid());
                    if (StringUtils.isNotBlank(locationDataJson)) {
                        LocationData locationData = JSONObject.parseObject(locationDataJson, LocationData.class);
                        if (DateUtil.isSameDate(new Date(locationData.getLocTime()), today)) {// 非当天的不提供
                            locationData.setUserName(val.getUserName());
                            onlineLocations.add(locationData);
                        }
                    }
                }
            }
            content.put("locationData", onlineLocations);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void getSelectLocation(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            JSONObject userJsonObj = json.getJSONObject("user");
            JSONArray uidsJSONArray = userJsonObj.getJSONArray("uids");
            if (uidsJSONArray == null || uidsJSONArray.size() == 0) {
                throw new Exception("缺少参数uids");
            }

            List<LocationData> selectLocations = new ArrayList<>();
            for (int i = 0; i < uidsJSONArray.size(); i++) {
                long uid = uidsJSONArray.getLongValue(i);
                String locationDataJson = RedisHelper.getUserLocationData(uid);
                if (StringUtils.isNotBlank(locationDataJson)) {
                    LocationData locationData = JSONObject.parseObject(locationDataJson, LocationData.class);
                    UserBasic user = JSONObject.parseObject(RedisHelper.getUser(uid), UserBasic.class);
                    locationData.setUserName(user.getUserName());
                    selectLocations.add(locationData);
                }
            }
            content.put("locationData", selectLocations);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void locationSwitch(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            JSONObject userJsonObj = json.getJSONObject("user");
            JSONArray uidsJSONArray = userJsonObj.getJSONArray("uids");
            long partyId = getPartyId(response.getAppId(), response.getAppType());

            CheckUtil.checkGetLocationSwitch(userJsonObj, uidsJSONArray);

            long locFlag = userJsonObj.getLongValue("locFlag");
            long locInterval = userJsonObj.getLongValue("locInterval") < 60 ? 60 : userJsonObj.getLongValue("locInterval");
            for (int i = 0; i < uidsJSONArray.size(); i++) {
                long uid = uidsJSONArray.getLongValue(i);
                userService.updateLocationFlag(uid, locFlag, locInterval);
            }
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void createPersonalRoom(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {

            Room queryBean = JSONObject.parseObject(json.get("room").toString(), Room.class);
            long[] uids = queryBean.getUids();
            String roomName = queryBean.getName();
            long partyId = queryBean.getPartyId();
            queryBean.createRoomCheck();

            UserOrg org = userService.getRootOrgByPartyId(partyId);
            if (uids.length < 2) {
                throw new Exception("参数uids至少2个人");
            }
            RoomBasic roomBasic = new RoomBasic();
            roomBasic.setStyle(4L);
            roomBasic.setName(roomName);
            roomBasic.setCapacity(1000l);
            roomBasic.setExpireType(queryBean.getExpireType());
            roomBasic.setHour(queryBean.getHour());
            roomBasic.setLoginType(1l);
            roomBasic.setEnterCtrl(1l);
            roomBasic.setOfflineCtrl(1l);
            roomBasic.setPttCtrl(2l);//优先级对讲，高级可抢夺
            roomBasic.setOwnerId(queryBean.getOwnerId());
            roomBasic.setPartyId(org.getPartyId());
            roomBasic.setOrgId(org.getOrgId());
            roomBasic.setOrgCode(org.getOrgCode());

            roomBasic.setWin1(100l);
            roomBasic.setWin2(15l);
            roomBasic.setWin3(15l);
            roomBasic.setWin4(15l);
            roomBasic.setWin5(15l);
            logger.info(JSONObject.toJSONString(roomBasic));
            RoomBasic roomBasicFDB = roomService.createPersonRoomBasic(roomBasic, uids);

            roomService.updateRoomBasicVersion(roomBasicFDB.getRid());
            for(long uid :uids) {
                roomService.updateRoomMemberVersion(uid, roomBasicFDB.getRid());
            }

            if(NumberUtils.isNotNullOrZero(queryBean.getShareVideoUid())){
                SysMsg sysMsg = new SysMsg();
                sysMsg.setCmdType(GlobalConstant.IMS_EVENT_QUEUE);
                sysMsg.setMsgType(GlobalConstant.MSG_TYPE_SHARE_VIDEO);
                sysMsg.setSndId(10000);
                sysMsg.setRcvId(queryBean.getShareVideoUid());
                HashMap msg = new HashMap();
                msg.put("type","rid");
                msg.put("id",roomBasic.getRid());
                sysMsg.setMsg(JSONObject.toJSONString(msg));
                List<SysMsg> sysMsgList = new ArrayList<SysMsg>();
                sysMsgList.add(sysMsg);
                tp.execute(new SysMsgThread(sysMsgList));
            }

            content.put("room", roomBasic);

            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void shareVideo(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {

            JSONObject data = json.getJSONObject("data");

            long shareUid = data.getLongValue("uid");
            long targetId = data.getLongValue("targetId");
            String targetType = data.getString("targetType");


            if(NumberUtils.isNotNullOrZero(shareUid)&& NumberUtils.isNotNullOrZero(targetId)){
                SysMsg sysMsg = new SysMsg();
                sysMsg.setCmdType(GlobalConstant.IMS_EVENT_QUEUE);
                sysMsg.setMsgType(GlobalConstant.MSG_TYPE_SHARE_VIDEO);
                sysMsg.setSndId(10000);
                sysMsg.setRcvId(shareUid);
                HashMap msg = new HashMap();
                msg.put("type",targetType);
                msg.put("id",targetId);
                sysMsg.setMsg(JSONObject.toJSONString(msg));
                List<SysMsg> sysMsgList = new ArrayList<SysMsg>();
                sysMsgList.add(sysMsg);
                tp.execute(new SysMsgThread(sysMsgList));

                data.put("resultCode","0000");

            }else{
                data.put("resultCode","0099");
                data.put("resultMsg","uid 或者 targetId 为0或者为空");
            }
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");

        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void addOrg(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            UserOrg org = JSONObject.parseObject(json.get("org").toString(), UserOrg.class);
            Org rtnOrg = new Org();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            try {

                CheckUtil.checkAddOrg(org);
                if (partyId != 0 && org.getPartyId().longValue() != partyId) {
                    throw new Exception("参数partyId数据异常");
                }
                UserOrg orgFDB = userService.saveUserOrg(org);

                BeanUtils.copyProperties(rtnOrg, orgFDB);

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("组织添加接口", e);
                rtnOrg.setErrorResultCode();
                rtnOrg.setResultMsg(e.getMessage());
            }
            content.put("org", rtnOrg);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }


    private void modOrg(ResponseBusiRecord response, JSONObject json) {

        JSONObject content = new JSONObject();
        try {
            UserOrg org = JSONObject.parseObject(json.get("org").toString(), UserOrg.class);
            Org rtnOrg = new Org();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            try {
                BeanUtils.copyProperties(rtnOrg, org);
                CheckUtil.checkModOrg(org);

                UserOrg userOrgFDB = userService.queryUserOrgByOrgId(org.getOrgId());
                if (partyId != 0 && userOrgFDB.getPartyId().longValue() != partyId) {
                    throw new Exception("参数partyId数据异常");
                }
                userOrgFDB.setOrgName(org.getOrgName());
                userService.saveUserOrg(userOrgFDB);
                BeanUtils.copyProperties(rtnOrg, userOrgFDB);
            } catch (Exception e) {
                logger.info("组织修改接口" + e.getMessage(), e);
                rtnOrg.setErrorResultCode();
                rtnOrg.setResultMsg(e.getMessage());
                e.printStackTrace();

            }
            content.put("org", rtnOrg);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            logger.info("组织修改接口" + e.getMessage(), e);
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }


    private void delOrg(ResponseBusiRecord response, JSONObject json) {
        JSONObject content = new JSONObject();
        try {
            UserOrg org = JSONObject.parseObject(json.get("org").toString(), UserOrg.class);
            Org rtnOrg = new Org();
            long partyId = getPartyId(response.getAppId(), response.getAppType());
            try {
                BeanUtils.copyProperties(rtnOrg, org);
                CheckUtil.checkDelOrg(org);
                if (partyId != 0) {
                    org.setPartyId(partyId);
                }
                userService.delUserOrg(org.getPartyId(), org.getOrgId());

            } catch (Exception e) {
                rtnOrg.setErrorResultCode();
                rtnOrg.setResultMsg(e.getMessage());
                e.printStackTrace();
                logger.error("组织删除接口", e);
            }

            content.put("org", rtnOrg);
            response.setResponseContent(content.toString());
            response.setResponseCode("0000");
        } catch (Exception e) {
            response.setResponseCode("0099");
            e.printStackTrace();
            response.setResponseCode("0099");
            if (e.getMessage() != null) {
                response.setResponseMsg(e.getMessage().length() > 1000 ? e.getMessage().substring(0, 990) : e.getMessage());
            }
        }
    }

    private void saveApiBusiRecord(ResponseBusiRecord response, Long partyId, Long uid, Long roomId) throws Exception {
//        ApiBusiRecord apiBusiRecord = new ApiBusiRecord();
//        apiBusiRecord.setMethod(response.getMethod());
//        apiBusiRecord.setTransactionId(response.getTransactionId());
//        apiBusiRecord.setPartyId(partyId);
//        apiBusiRecord.setUid(uid);
//        apiBusiRecord.setChannelId(roomId);
//        apiService.saveApiBusiRecord(apiBusiRecord);
    }

    private String getToken(String appId, String appType) {
        if ("C".equalsIgnoreCase(appType)) {
            if (!companyTokenMap.containsKey(appId)) {
                UserParty party = userService.getUserPartyById(NumberUtils.toLong(appId));
                if (party != null) {
                    String token = party.getPartyKey();
                    companyTokenMap.put(appId, token);
                } else {
                    return null;
                }

            }
            return companyTokenMap.get(appId);
        } else if ("S".equalsIgnoreCase(appType)) {
            if (!systemTokenMap.containsKey(appId)) {
                SysStaticData tokenSysStaticData = staticDataCache.getValue("token", appId);
                if (tokenSysStaticData != null) {
                    String token = tokenSysStaticData.getCodeName();
                    systemTokenMap.put(appId, token);
                } else {
                    return null;
                }

            }
            return systemTokenMap.get(appId);
        }
        return null;

    }


    private long getPartyId(String appId, String appType) {
        long partyId = 0;
        if ("C".equalsIgnoreCase(appType)) {
            partyId = NumberUtils.toLong(appId, 0);
        }
        return partyId;
    }


    protected RoomBasic initRoomBasic(RoomBasic roomBasic) {
        roomBasic.setExpireType(1L);
        roomBasic.setLoginType(1L);
        roomBasic.setEnterCtrl(1L);
        roomBasic.setOfflineCtrl(1L);
        roomBasic.setCapacity(1000L);
        if (roomBasic.getStyle().longValue() == GlobalConstant.ROOM_STYLE_1) {//语音
            roomBasic.setWin1(100L);//无视频|16k语音|自动麦
        } else if (roomBasic.getStyle().longValue() == GlobalConstant.ROOM_STYLE_3) {//视频对讲
            roomBasic.setWin1(100L);//无视频|16k语音|自动麦
            roomBasic.setWin2(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin3(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin4(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin5(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin6(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin7(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin8(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin9(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin10(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin11(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin12(15L);//视频窗口640x480码率300k|音频16khz|自动麦
        }
        return roomBasic;
    }
}
